import React, { useState } from "react";

const FormStatus = () => {
	const [ answer, setAnswer ] = useState( '' );
	const [ status, setStatus ] = useState( 'typing' );
	const [ error, setError ] = useState<Error | null>( null );
	if( status === 'success' ) {
		return <h1>That‘s right!</h1>
	}

	const handleSubmit = async (e:React.FormEvent<HTMLFormElement>) => {
		e.preventDefault();
		setStatus( 'submitting' );
		try {
			setStatus( 'loading' );
			await submitForm(answer);
			setStatus( 'success' );
		} catch ( err ) {
			const error = err instanceof Error ? err : new Error(String(err));
			setError(error);
			setStatus( 'typing' );
		}
	};

	const handleTextChange = (e:React.ChangeEvent<HTMLTextAreaElement>) => {
		setAnswer( e.target.value );
	};

	return (
		<>
			<h2>City quiz</h2>
			<p>
				In which city is there a billboard that turns air into drinkable water?
			</p>
			<form onSubmit={ handleSubmit }>
				<textarea value={ answer} onChange={handleTextChange} disabled={status === 'submitting'}></textarea>
				<br />
				<button disabled={ answer.length=== 0 || status === 'submitting'}>
					Submit
				</button>
				{error !== null && <p className="Error">{error.message}</p>}
			</form>
		</>
	);
}

const submitForm = (answer: string) : Promise<void> => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			let shouldError = answer.toLowerCase() !== 'lima';
			if (shouldError) {
				reject(new Error('Good guess but a wrong answer. Try again!'));
			} else {
				resolve();
			}
		}, 1500);
	});
}

export default FormStatus;